//
//  YSLMainTabBar.swift
//  SinaWeibo
//
//  Created by 嵩雷 on 16/3/6.
//  Copyright © 2016年 嵩雷. All rights reserved.
//

import UIKit

class YSLMainTabBar: UITabBar {
    
    var composeButtonClosure: (()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        addSubview(composeButton)
    }
    
//    按钮初始化: 属性
   private lazy var composeButton: UIButton = {
        let button = UIButton()
    
    //给按钮添加点击事件（因为button最重要的就是点击事件，所以写在前面）
    button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
    
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        button.sizeToFit()
        return button
    }()
    
 @objc private func composeButtonClick(){
    composeButtonClosure?()
    }
//    按钮初始化: 坐标
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
//        composeButton.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
        
        ///每一个按钮的宽度
        let childW = frame.size.width / 5
        //定义脚标记录当前button的位置
        var index = 0
        
        //遍历子控件调整'UITabBarButton'的宽度与位置
        for childView in subviews {
            
            //如果当前遍历的View是UITabBarButton
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                //设置按钮的宽
                childView.frame.size.width = childW
                //设置按钮的x
                childView.frame.origin.x = CGFloat(index) * childW
                //index递增
                index++
                //如果当前遍历到'发现'，则把发现往后移动一个位置
                if index == 2 {
                    index++
                }
            }
        }
    }

}
